<?php

namespace Wap\Model;

class UserOrderModel extends BaseModel {

    /**
     * 用户订单列表
     * @param type $userId
     * @return type
     */
    public function orderList($userId, $orderStatus) {
        $m = M('orders');
        $num = 5;
        $page = I('page') ? I('page') : 1;
        $current = $page;
        $page = ($page - 1) * $num;

        if ($orderStatus == 2) {
            $statusSql = ' AND orderStatus IN (2,3,4,5,6) ';
        } else {
            $statusSql = ' AND orderStatus = ' . $orderStatus;
        }

        $order['count'] = $m->where('orderFlag = 1 AND orderStatus = ' . $orderStatus . ' AND userId=' . $userId)->count();
        $order['num'] = $num;
        $order['current'] = $current;
        $order['sumpage'] = ceil($order['count'] / $num);

        $orderList = M('orders')->where('orderFlag = 1 and orderSN != 0 ' . $statusSql . ' AND userId=' . $userId)->field('orderId,orderNo,totalMoney,postage,supPrice,supPostage,payType,buyway,(totalMoney+postage+supPrice+supPostage) as priceSum,orderStatus,expressId,expressNo,isSource')->order('orderId DESC')->limit($page, $num)->select();
        if (empty($orderList))
            return;

        $data = array();
        foreach ($orderList as $v) {
            $v['goods'] = M('order_goods')->where('orderId=' . $v['orderId'])->select();
            $v['expressName'] = M('express')->where('expressId=' . $v['expressId'])->getField('expressName');
            $data[] = $v;
        }
        $order['order'] = $data;

        return $order;
    }

    /**
     * 用户订单列表
     * @param type $userId
     * @return type
     */
    public function allOrderList($userId) {
        $m = M('orders');
        $num = 5;
        $page = I('page') ? I('page') : 1;
        $current = $page;
        $page = ($page - 1) * $num;

        $order['count'] = $m->where('orderFlag = 1 AND userId=' . $userId)->count();
        $order['num'] = $num;
        $order['current'] = $current;
        $order['sumpage'] = ceil($order['count'] / $num);

        $orderList = M('orders')->where('orderFlag = 1 AND userId=' . $userId)->field('orderId,orderNo,totalMoney,postage,supPrice,supPostage,payType,buyway,orderStatus')->order('orderId DESC')->limit($page, $num)->select();
        if (empty($orderList))
            return;

        $data = array();
        foreach ($orderList as $v) {
            $v['goods'] = M('order_goods')->where('orderId=' . $v['orderId'])->select();
            $data[] = $v;
        }
        $order['order'] = $data;

        return $order;
    }

    /**
     * 取消订单
     * @return type
     */
    public function cancelOrder($userId) {
        $m = M('orders');
        $orderId = I('orderId', 0);
        $m->orderFlag = 0;
        $rs = $m->where('orderId=' . $orderId . ' and userId=' . $userId)->save();

        return $rs;
    }

    /**
     * 待付款订单结算
     * @return type
     */
    public function toCheckPay($userId) {
        $rt = array();
        $rt['code'] = 0;
        $rt['info'] = 'Error!';

        $m = M('orders');
        $orderId = I('orderId', 0);

        $m = M('orders');
        $order = $m->where('orderId=' . $orderId . ' and userId=' . $userId)->field('orderId,orderNo,orderStatus,shopId,totalMoney,postage,supPrice,supPostage,payType,buyway,userName,userAddress,userPhone,storeId,createTime')->find();
        if (empty($order))
            return $rt;
        $sql = 'select u.userId,u.userName,u.userPhoto from __PREFIX__shops as s left join __PREFIX__users as u on s.userId = u.userId where s.shopId = ' . $order['shopId'];
        $order['shopInfo'] = $this->queryRow($sql);
 //       $getOrderGoods = $this->getOrderGoods($orderId);
        $getOrderGoods = $this->orderInfo($orderId);
//prt($getOrderGoods);        
        $order['priceSum'] = $getOrderGoods['totalMoney'] + $order['postage'] + $order['supPrice'] + $order['supPostage'];
        $order['payTypeName'] = M('payments')->where('id=' . $order['payType'])->getField('payName');
        $order['buywayName'] = M('buyway')->where('id=' . $order['buyway'])->getField('buyName');

        $order['goodsNumber'] = M('order_goods')->where('orderId=' . $orderId)->getField('sum(goodsNumber) as goodsNumber');
        $order['goods'] = $getOrderGoods['goods'];
        $order['buywayList'] = M('buyway')->field('id,buyCode,buyName,buyConfig')->select();
        $order['payments'] = M('payments')->field('id,payCode,payName')->select();
        if ($order['buyway'] == 2) {
            $order['linestore'] = M('linestore')->where('storeId=' . $order['storeId'])->field('storeId,storeName,storeAddress,province,city,district,storeTel')->find();
        }

        $rt['code'] = 1;
        $rt['info'] = 'Success!';
        $rt['data'] = $order;
        return $rt;
    }

    /**
     * 提醒发货
     * @param type $userId
     * @return boolean
     */
    public function remind($userId) {
        $orderId = I('orderId', 0);

        return TRUE;
    }

    /**
     * 订单详情
     * @return type
     */
    public function orderInfo($userId) {
        $m = M('orders');
        $orderId = I('orderId', 0);

        $order = $m->where('orderId=' . $orderId)->field('orderId,orderNo,orderStatus,shopId,totalMoney,postage,supPrice,supPostage,payType,buyway,userName,userAddress,userPhone,storeId,expressId,expressNo,createTime,isSource')->find();
        if (empty($order))
            return $order;
        if ($userId != $order['userId'] && ($order['isSource'] = 0 || $order['buyway'] == 3)) {
            $order['userName'] = M('sys_configs')->where('fieldCode = "yuduUserName"')->getField('fieldValue');
            $order['userAddress'] = M('sys_configs')->where('fieldCode = "yuduAddress"')->getField('fieldValue');
            $order['userPhone'] = M('sys_configs')->where('fieldCode = "yuduPhone"')->getField('fieldValue');
        }
        $sql = 'select u.userId,u.userName,u.userPhoto from __PREFIX__shops as s left join __PREFIX__users as u on s.userId = u.userId where s.shopId = ' . $order['shopId'];
        $order['shopInfo'] = $this->queryRow($sql);
        $order['priceSum'] = $order['totalMoney'] + $order['postage'] + $order['supPrice'] + $order['supPostage'];
        $order['payTypeName'] = M('payments')->where('id=' . $order['payType'])->getField('payName');
        $order['buywayName'] = M('buyway')->where('id=' . $order['buyway'])->getField('buyName');
        $order['goods'] = M('order_goods')->where('orderNo=' . $order['orderNo'])->select();
        $order['expressName'] = M('express')->where('expressId=' . $order['expressId'])->getField('expressName');
        if (empty($order['expressName']))
            $order['expressName'] = '';

        if ($order['buyway'] == 2) {
            $order['linestore'] = M('linestore')->where('storeId=' . $order['storeId'])->field('storeId,storeName,storeAddress,province,city,district,storeTel')->find();
            if (empty($order['linestore']))
                $order['linestore'] = array();
        }

        return $order;
    }

    /**
     * 确认收货
     * @param type $userId
     * @return boolean
     */
    public function confirm($userId) {
        $orderId = I('orderId', 0);
        $m = M('orders');
//        $rs = $m->where('orderStatus = 1 AND orderId = ' . $orderId . ' AND userId = ' . $userId)->save(array('orderStatus' => 2));
//        $orderInfo = $m->where('orderId = ' . $orderId)->find();

        $orderInfo = $m->where('orderId = ' . $orderId)->find();
        $rs = $m->where(' orderNo = ' . $orderInfo['orderNo'] . ' AND userId = ' . $userId)->save(array('orderStatus' => 2, 'upTime' => date('Y-m-d H:i:S')));

        $userPhone = M('shops')->where('shopId = ' . $orderInfo['shopId'])->getField('shopTel');
        if($orderInfo['isSource'] == 1) {
            D('Wap/Sms')->sendSMScode($userPhone, array($vs['goodsName']), 'odfinishTempId', 'odfinishTempId');
        } else {
            D('Wap/Sms')->sendSMScode($userPhone, array($vs['goodsName']), 'reodfinishTempId', 'reodfinishTempId');
        }

        return $rs;
    }

    /**
     * 快递信息
     * @param type $userId
     * @return boolean
     */
    public function expressNo($userId) {
        $orderId = I('orderId', 0);
        $data = array('expressName' => '圆通速递', 'expressNo' => '700074134800');

        return $data;
    }

    /**
     * 商品评价
     * @param type $userId
     * @return boolean
     */
    public function appraises($userId) {
        $orderId = I('orderId', 0);
        $goodsId = I('goodsId', 0);

        $shopId = M('orders')->where('orderId=' . $orderId)->getField('shopId');
        $rs = M('order_goods')->where('orderId=' . $orderId . ' and goodsId = ' . $goodsId)->getField('isAppraises');
        if ($rs != FALSE)
            return $rs;

        $data = array();
        $data['orderId'] = $orderId;
        $data['shopId'] = $shopId;
        $data['goodsId'] = $goodsId;
        $data['userId'] = $userId;
        $data['goodsScore'] = I('goodsScore');
        $data['serviceScore'] = I('goodsScore');
        $data['timeScore'] = I('goodsScore');
        $data['content'] = I('content');
        $data['createTime'] = date('Y-m-d H:i:s');

        $rs = M('goods_appraises')->add($data);
        M('order_goods')->where('orderId=' . $orderId . ' and goodsId = ' . $goodsId)->save(array('isAppraises' => 1));

        return $rs;
    }

    /**
     * 售后信息
     * @param type $userId
     * @return boolean
     */
    public function serviceInfo($userId) {
        $orderId = I('orderId', 0);
        $m = M('orders');
        $data = array('expressName' => '圆通速递', 'expressNo' => '700074134800');
        $order = $m->where('orderStatus in (2,3,4,5) and orderId=' . $orderId . ' and userId = ' . $userId)->field('orderId,orderNo,orderStatus,shopId')->find();
        if (empty($order))
            return $order;
        $order['goods'] = M('order_goods')->where('orderId=' . $orderId)->select();

        return $order;
    }

    /**
     * 提交退货
     * @param type $userId
     * @return boolean
     */
    public function returnGoods($userId) {
        $goodsId = I('goodsId', 0);
        $orderId = I('orderId', 0);

        if ($goodsId == 0 || $orderId == 0)
            return FALSE;

        $order = M('orders')->where('orderStatus = 2 and orderId=' . $orderId . ' and userId = ' . $userId)->field('orderId,orderNo,orderStatus,shopId')->find();
        if (empty($order))
            return $order;
        $goodsId = explode(',', $goodsId);
        $content = I('content');
        $pics = I('pics');

        $data = array();
        $data['orderId'] = $orderId;
        $data['userId'] = $userId;
        $data['shopId'] = $order['shopId'];
        $data['content'] = $content;
        $data['pics'] = json_encode(explode(',', trim($pics, ',')));

        $m = M('order_refund');
        foreach ($goodsId as $v) {
            $data['goodsId'] = $v;
            $rs = $m->add($data);
            if ($rs === FALSE)
                return FALSE;
        }
        $rs = M('orders')->where('orderStatus = 2 and orderId=' . $orderId . ' and userId = ' . $userId)->save(array('orderStatus' => 3));

        return TRUE;
    }

    /**
     * 自动更新用户订单状态
     * @param type $userId
     */
    public function upAutoOrderStatus($userId) {
        $m = M('orders');
        $date = date("Y-m-d", strtotime("-10 day"));
        $noComOrder = $m->where('orderStatus = 1 and userId = ' . $userId . ' and date_format(`createTime`, "%Y-%m-%d") <= "' . $date . '"')->field('orderId, orderNo, orderSN, date_format(`createTime`, "%Y-%m-%d") AS time ')->select();
        $noComOrderId = '';
        foreach ($noComOrder as $v) {
            $noComOrderId .= $v['orderId'] . ',';
        }
        $noComOrderId = trim($noComOrderId, ',');
        if (!empty($noComOrderId)) {
            $rs = $this->upOrderStatus($noComOrderId, 2);
        }

        $date = date("Y-m-d", strtotime("-3 day"));
        $noFinishOrder = $m->where('orderStatus = 2 and userId = ' . $userId . ' and date_format(`createTime`, "%Y-%m-%d") <= "' . $date . '"')->field('orderId, orderNo, orderSN, date_format(`createTime`, "%Y-%m-%d") AS time ')->select();
        $noFinishOrderId = '';
        foreach ($noFinishOrder as $v) {
            $noFinishOrderId .= $v['orderId'] . ',';
        }
        $noFinishOrderId = trim($noFinishOrderId, ',');

        if (!empty($noFinishOrderId)) {
            $rs = $this->upOrderStatus($noFinishOrderId, 6);
        }
    }

    /**
     * 用户订单数量统计
     */
    public function userOrderSum($userId) {
        $m = M('orders');
        $sum = array();
        $sum['nopay'] = $m->where('orderFlag = 1 and orderSN != 0 and orderStatus = -2 and userId = ' . $userId)->count();
        $sum['noshipping'] = $m->where('orderFlag = 1 and orderSN != 0 and orderStatus = 0 and userId = ' . $userId)->count();
        $sum['server'] = $m->where('orderFlag = 1 and orderSN != 0 and orderStatus in(2,3,4,5,6,-3) and userId = ' . $userId)->count();
        $sum['nosign'] = $m->where('orderFlag = 1 and orderSN != 0 and orderStatus = 1 and userId = ' . $userId)->count();

        return $sum;
    }

    /**
     * 销售订单数量统计
     */
    public function shopOrderSum($userId) {
        $m = M('orders');
        $shopId = M('shops')->where('userId=' . $userId)->getField('shopId');
        $sum = array();
        $sum['nopay'] = $m->where('orderFlag = 1 and orderStatus = -2 and shopId = ' . $shopId)->count();
        $sum['noshipping'] = $m->where('orderFlag = 1 and orderStatus = 0 and shopId = ' . $shopId)->count();
        $sum['server'] = $m->where('orderFlag = 1 and orderStatus in(2,3,4,5) and shopId = ' . $shopId)->count();
        $sum['nosign'] = $m->where('orderFlag = 1 and orderStatus = 1 and shopId = ' . $shopId)->count();

        return $sum;
    }

    /**
     * 待付款订单结算
     * @return type
     */
    public function toServer($userId) {
        $rt = array();
        $rt['code'] = 0;
        $rt['info'] = 'Error!';

        $m = M('orders');
        $orderId = I('orderId', 0);

        $m = M('orders');
        $order = $m->where('orderId=' . $orderId . ' and userId=' . $userId)->field('orderId,orderNo,orderStatus,shopId,totalMoney,postage,supPrice,supPostage,payType,buyway,userName,userAddress,userPhone,storeId,createTime')->find();
        if (empty($order))
            return $rt;
        $order['goods'] = M('order_goods')->where('orderId = ' . $orderId)->find();

        $rt['code'] = 1;
        $rt['info'] = 'Success!';
        $rt['data'] = $order;
        return $rt;
    }

}
